﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

namespace Extend.Pool
{
    [Obsolete("请使用PoolManager代替")]
	public static class ReferencePoolUtility
    {
        /*
         引用类型池
             */
	    public static void Clear()
	    {
	        lock (_lockObject)
	        {
	            _pool.Clear();
	        }
	    }
	    
	    public static T Spawn<T>()
	    {
	        T result;
	        lock (_lockObject)
	        {
                if (_pool.TryGetValue(typeof(T),out object stackObj))
                {
                    Stack<T> stack = stackObj as Stack<T>;
                    if (stack.Count > 0)
                    {
                        return stack.Pop();
                    }
                }
                result = (T)((object)CreateInstance(typeof(T)));
	        }
	        return result;
	    }
	
	    public static void Recycle<T>(T obj)
	    {
	        if (obj == null)
	        {
	            return;
	        }
	        lock (_lockObject)
	        {
	            if (_pool.TryGetValue(typeof(T), out object stackObj))
	            {
	                Stack<T> stack = stackObj as Stack<T>;
	                stack.Push(obj);
	            }
	            else
	            {
	                Stack<T> stack2 = new Stack<T>();
	                stack2.Push(obj);
	                _pool.Add(typeof(T), stack2);
	            }
	        }
	    }

        private static object CreateInstance(Type t)
        {
            if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                t = Nullable.GetUnderlyingType(t);
            }
            return Activator.CreateInstance(t, true);
        }

        private static object _lockObject = new object();
	
	    private static Dictionary<Type, object> _pool = new Dictionary<Type, object>();
	}
}
